package com.mycat.chat.two.socket.client;

import com.mycat.chat.two.util.Constants;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * 聊天NIO客户端
 *
 * @author roger.
 * @email 190642964@qq.com
 * @create 2017-02-24
 */
public class ChatNIOClient {

    private SocketChannel client;
    private Selector selector;
    // 服务端地址
    private InetSocketAddress serverAddress = new InetSocketAddress("localhost", Constants.NIO_PORT);
    ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
    ByteBuffer sendBuffer = ByteBuffer.allocate(1024);


    public ChatNIOClient() throws IOException {
        // 打开Socket通道
        client = SocketChannel.open();
        // 设置为非阻塞
        client.configureBlocking(false);
        // 连接服务端
        client.connect(serverAddress);
        // 打开Selector
        selector = Selector.open();
        // selector注册
        client.register(selector, SelectionKey.OP_ACCEPT);

        if (client.isConnectionPending()) {
            System.out.println("客户端正常连接ChatServer..........");
            client.finishConnect();
            client.register(selector, SelectionKey.OP_WRITE);
        }else{
            System.out.println("客户端没有连接上ChatServer............");
        }
    }

    public void process(String name) throws IOException {
        boolean unFinish = true;
        while (unFinish) {
            // 判断当前有没有客户来注册，有没有排队的，有没有取号的
            int i = selector.select();
            if (i == 0) {
                continue;
            }

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = keys.iterator();

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();

                if (key.isWritable()) {

                    sendBuffer.clear();
                    sendBuffer.put(name.getBytes());
                    sendBuffer.flip();

                    client.write(sendBuffer);

                    client.register(selector,SelectionKey.OP_READ);

                } else if (key.isReadable()) {

                    receiveBuffer.clear();
                    int len = client.read(receiveBuffer);
                    if(len > 0){
                        receiveBuffer.flip();
                        System.out.println("获取到服务端反馈的消息："+new String(receiveBuffer.array(),0,len));
                        client.register(selector,SelectionKey.OP_WRITE);
                        unFinish = false;
                    }


                }
            }
        }
    }

}
